﻿
Namespace PL.MESSDK
    Public Class SampleHeader_PL
        Inherits PLBase

        Public Sub New(ByVal queryName As String)
            MyBase.New(queryName)
        End Sub
        Public Sub New()
            MyBase.New()
        End Sub

        Sub OnRowUpdating(ByVal sender As Object, ByVal e As SqlRowUpdatingEventArgs) Handles MetaDataTable.OnRowUpdating
        End Sub

        Public Overrides Function Delete() As Boolean
            'Throw New NotImplementedException("Delete To Come...")
            Return False
        End Function

        Public Overrides Function Validate() As Boolean
            'Throw New NotImplementedException("Validate To Come...")
            Return True
        End Function
        Public Overridable Function CreateNewQASheet(ByVal lotId As Guid, ByVal lotDescription As String, ByVal requestedQty As Double, ByVal unitId As Guid, Optional ByVal referenceDocument As String = Nothing) As Boolean
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("CreateNewLot")
                '
                '@NewLotId UniqueIdentifier = NULL,
                '@LotTypeID_FK UniqueIdentifier, 
                '@LotCD varchar(50), 
                '@WhouseID_FK UniqueIdentifier,
                '@WhBinID_FK UniqueIdentifier,
                '@PrdID_FK UniqueIdentifier,
                '@EquipmentId_FK UniqueIdentifier,
                '@RequestedQty Decimal(18,3),
                '@SampleQty Decimal(18,3),
                '@SampleUnitID_FK UniqueIdentifier,
                '@StatusID_FK UniqueIdentifier,
                '@StartDate datetime,
                '@RequiredDate datetime
                '
                'sqlcmd.Parameters("@LotID").Value = lotId
                'sqlcmd.Parameters("@TOLotStatusId_FK").Value = statusId
                'sqlcmd.Parameters("@RefDoc").Value = referenceDocument
                'sqlcmd.Parameters("@LotID").Value = lotId
                'sqlcmd.Parameters("@TOLotStatusId_FK").Value = statusId
                'sqlcmd.Parameters("@RefDoc").Value = referenceDocument
                ''
                sqlcmd.ExecuteNonQuery()
                Return True
            Catch sqlex As System.Data.SqlClient.SqlException
                Throw
            Catch ex As Exception
                Throw
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Dispose()
                End If
            End Try
        End Function

        ''' <summary>
        ''' This function validate, through a DB query, if the same LotSerialNo has already been use, witch is not allowed.
        ''' </summary>
        ''' <param name="aLotSerialNo"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Overridable Function GetByLotSerialNo(ByVal aLotSerialNo As String, ByVal QAQCInspLotID As Guid) As Boolean
            Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
            Try
                Dim mq As MetaQuery = MetaQuery.GetMetaQueryByName("SampleHeader_GetByLotSerialNo")
                Dim exist As Boolean = False
                mq.SQLWhere = String.Format("LotSerialNo = '{0}' and QAQCInspLotID <> '{1}'", aLotSerialNo, QAQCInspLotID)
                mq.FillResultQuery()

                If mq.ResultQuery.Rows.Count = 1 AndAlso mq.ResultQuery.Rows(0)("Count") = 1 Then
                    exist = True
                End If

                Return exist

            Catch sqlex As System.Data.SqlClient.SqlException
                Throw
            Catch ex As Exception
                Throw
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Dispose()
                End If
            End Try
        End Function


       

        ''' <summary>
        ''' This function validate, through the grid, if the same LotSerialNo has already been use, witch is not allowed.
        ''' </summary>
        ''' <param name="aRow"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function ValidLotSerialNo(ByVal aRow As DataRow) As Boolean

            Dim rowGUID As Guid = CType(aRow("QAQCInspLotID"), Guid)
            Dim rowLotSerialNo As String = aRow("LotSerialNo").ToString

            For Each row As DataRow In aRow.Table.Rows
                If CType(row("QAQCInspLotID"), Guid) <> rowGUID And row("LotSerialNo").ToString.Contains(rowLotSerialNo) Then
                    Return False
                End If
            Next



            Return True

        End Function


        ''' <summary>
        ''' Validate a SampleHeader DataRow
        ''' </summary>
        ''' <param name="row"></param>
        ''' <remarks>Errors are saved with row.SetColumnError method</remarks>
        Public Overrides Sub ValidateRow(row As DataRow)
            row.ClearErrors()
            'Mandatory Fields
            'TODO: Cache MetaString in AppManager, so here we read it once maybe for nothing
            'Dim ms As MetaString
            'ms = MetaString.GetMetaStringByCode("Mandatory", AppManager.ApplicationOption.LanguageId)


            If row.Table.Columns.Contains("LotTypeID_FK") Then
                If IsDBNull(row("LotTypeID_FK")) Then
                    row.SetColumnError("LotTypeID_FK", "Mandatory")
                End If
            End If
            If row.Table.Columns.Contains("LotDescr_Prm") Then
                If IsDBNull(row("LotDescr_Prm")) Then
                    row.SetColumnError("LotDescr_Prm", "Mandatory")
                End If
            End If

            If row.Table.Columns.Contains("LotSerialNo") Then
                If Not IsDBNull(row("LotSerialNo")) Then

                    If GetByLotSerialNo(row("LotSerialNo").ToString, row("QAQCInspLotID")) Then
                        row.SetColumnError("LotSerialNo", "Duplicate")

                    ElseIf String.IsNullOrEmpty(row("LotSerialNo").ToString) Then
                        row.SetColumnError("LotSerialNo", "Mandatory")

                    ElseIf Not ValidLotSerialNo(row) Then
                        row.SetColumnError("LotSerialNo", "Duplicate")
                    End If

                End If
            End If


            If row.Table.Columns.Contains("WhouseID_FK") Then
                If IsDBNull(row("WhouseID_FK")) Then
                    row.SetColumnError("WhouseID_FK", "Mandatory")
                End If
            End If

            If row.Table.Columns.Contains("PrdID_FK") Then
                If IsDBNull(row("PrdID_FK")) Then
                    row.SetColumnError("PrdID_FK", "Mandatory")
                End If
            End If


            If Not IsDBNull((row("WhouseID_FK"))) Then
                Dim aSiteRow As DataRow = Site_PL.GetSiteByID(DirectCast(row("WhouseID_FK"), Guid))

                If aSiteRow IsNot Nothing AndAlso Not IsDBNull(aSiteRow("SocietyID_FK")) Then

                    Dim aSocietyRow As DataRow = Society_PL.GetSocietyByID(DirectCast(aSiteRow("SocietyID_FK"), Guid))
                    If aSocietyRow IsNot Nothing Then
                        Dim societyCD As String = aSocietyRow("SocietyCd").ToString

                        Select Case societyCD
                            Case "30", "07"
                                'Mode MES: 30=Rosell, 07=St-Simon
                                If row.Table.Columns.Contains("LotId_FK") Then
                                    If IsDBNull(row("LotId_FK")) Then
                                        row.SetColumnError("LotId_FK", "Mandatory")
                                    End If
                                End If

                                If row.Table.Columns.Contains("LotRoutingId_FK") Then
                                    If IsDBNull(row("LotRoutingId_FK")) Then
                                        row.SetColumnError("LotRoutingId_FK", "Mandatory")
                                    End If
                                End If

                            Case "83", "04"
                                'Mode LIMS: 83=Wien, 04=Baltimore
                                If row.Table.Columns.Contains("RoutingId_FK") Then
                                    If IsDBNull(row("RoutingId_FK")) Then
                                        row.SetColumnError("RoutingId_FK", "Mandatory")
                                    End If
                                End If

                            Case "01", "39"
                                'Mode LIMS: 01=Pref, 39=Memphis
                                If row.Table.Columns.Contains("RoutingId_FK") Then
                                    If IsDBNull(row("RoutingId_FK")) Then
                                        row.SetColumnError("RoutingId_FK", "Mandatory")
                                    End If
                                End If

                                If row.Table.Columns.Contains("EquipmentId_FK") Then
                                    If IsDBNull(row("EquipmentId_FK")) Then
                                        row.SetColumnError("EquipmentId_FK", "Mandatory")
                                    End If
                                End If

                                If row.Table.Columns.Contains("ProcessCode") Then
                                    If IsDBNull(row("ProcessCode")) Then
                                        row.SetColumnError("ProcessCode", "Mandatory")
                                    End If
                                End If

                        End Select
                    End If
                End If
            End If


            If row.Table.Columns.Contains("RequestedQty") Then
                If IsDBNull(row("RequestedQty")) Then
                    row.SetColumnError("RequestedQty", "Mandatory")
                End If
            End If
            '
            If row.HasErrors Then
                row.RowError = "Please check your columns, a validation error occur"
            End If
        End Sub
    End Class
End Namespace
